package cn.iotab.iotkit.transport.api.common.message.codec;

import cn.iotab.iotkit.queue.queue.QueueMsg;
import cn.iotab.iotkit.transport.api.common.message.JsonQueueMsg;
import cn.iotab.iotkit.transport.api.common.message.TransportMsg;
import cn.iotab.iotkit.transport.api.common.util.JsonUtil;

import java.io.IOException;

public class JsonMsgDecoder<T extends TransportMsg> implements QueueMsg.Decoder<JsonQueueMsg<T>> {

    private final Class<T> tClass;

    public JsonMsgDecoder(Class<T> tClass) {
        this.tClass = tClass;
    }

    @Override
    public JsonQueueMsg<T> decode(QueueMsg queueMsg) throws IOException {
        if (queueMsg == null) throw new NullPointerException("queueMsg is null");
        byte[] dat = queueMsg.getData();
        T rpcResponseMessage = JsonUtil.toObject(dat, tClass);
        return new JsonQueueMsg<>(queueMsg.getKey(), rpcResponseMessage, queueMsg.getHeaders());
    }
}
